import { Effect } from 'umi';
import { message } from 'antd';
import { fetchAllAppNotPage } from '@/services/app';
import { querySysDict } from '@/services/system';
import { fetchAllTrade, addTrade, updateTrade, deleteTrades, importTrade } from '@/services/trade';
import { AppItem } from '@/types/app';
import { DataItem, TradeResult } from '@/types/global';
import { TradeItem } from '@/types/trade';
import { BaseModelType } from './common';

export interface TradeModelState {
  rows?: TradeItem[];
  total?: number;
  pageSize?: number;
  systemData?: DataItem[];
  clusterData?: DataItem[];
  statusData?: DataItem[];
  appList?: AppItem[];
}

export interface TradeModelType extends BaseModelType {
  namespace: 'trades';
  state: TradeModelState;
  effects: {
    fetchTradeInitParams: Effect;
    fetchAllTrade: Effect;
    addTrade: Effect;
    updateTrade: Effect;
    deleteTrades: Effect;
    unMount: Effect;
    importTrade: Effect;
  };
  // reducers: {
  //   updateState: Reducer<ParamModelState>;
  // };
}

const TradeModel: TradeModelType = {
  namespace: 'trades',

  state: {
    rows: [],
    total: 0,
    pageSize: 10,
    statusData: [
      {
        key: '0',
        value: '生效'
      },
      {
        key: '1',
        value: '失效'
      }
    ],
  },

  effects: {
    *fetchTradeInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ systemResponse, clusterResponse, statusResponse, appListResponse ] = yield all([
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'cluster'
          }),
          call(querySysDict, {
            dictName: 'status'
          }),
          call(fetchAllAppNotPage, {})
        ]);
        // console.info(systemResponse);
        // console.info(clusterResponse);
        // console.info(statusResponse);
        const systemSuccess =  systemResponse.success;
        const clusterSuccess =  clusterResponse.success;
        const statusSuccess =  statusResponse.success;
        const appListSuccess =  appListResponse.success;
        if (systemSuccess && clusterSuccess && statusSuccess && appListSuccess) {
          const result  = {
            systemData: [...systemResponse.result],
            clusterData: [...clusterResponse.result],
            statusData: [...statusResponse.result],
            appList: [...appListResponse.result!.appList],
          };
          console.info(result);
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchAllTrade({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(fetchAllTrade, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          // 更新表格数据
          yield put({ type: 'updateState', payload: result });
        } else {
          // message.error(`${response.errorCode}:${response.errorMsg}`); // 打印错误信息
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *addTrade({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response = yield call(addTrade, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('新增成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('新增失败'); // 打印错误信息
        return false;
      }
    },
    *updateTrade({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response = yield call(updateTrade, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('更新成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('更新失败'); // 打印错误信息
        return false;
      }
    },
    *deleteTrades({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(deleteTrades, payload);
        // console.log(JSON.stringify(response));
        // yield call(delay, 3000);
        const { success } = response;
        if (success) {
          message.success('删除成功');
          // 刷新表格
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('删除失败'); // 打印错误信息
        return false;
      }
    },
    *unMount({ payload }, sagaEffects) {
      const { put } = sagaEffects;
      const result = {
        rows: [],
        total: 0,
        pageSize: 10,
        appList: []
      }
      yield put({ type: 'updateState', payload: result });
    },
    *importTrade({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(importTrade, payload);
        // console.log(JSON.stringify(response));
        // yield call(delay, 3000);
        const { success } = response;
        if (success) {
          message.success('批量导入成功，可刷新表格查看');
          // 刷新表格
          return true;
        } else {
          message.error('批量导入失败，请联系管理员');
          return false;
        }
      } catch(e) {
        console.error(e);
        message.error('批量导入失败，请联系管理员'); // 打印错误信息
        return false;
      }
    },
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default TradeModel;